package com.shanghaionstar.carmanage.presenter;

import android.Manifest;
import android.os.Bundle;
import android.util.Log;
import android.widget.AbsListView;

import com.onstar.cn.chargepile.entity.ChargePileReqEntity;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.mvp.base.core.PermissionCall;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.framework.utils.RxSubscriptions;
import com.onstar.cn.rxconstants.RxConstants;
import com.shanghaionstar.R;
import com.shanghaionstar.carmanage.chargpile.ChargePileStationLocationFragment;
import com.shanghaionstar.carmanage.iview.IChargingPileView;
import com.shanghaionstar.carmanage.model.ChargePileStationEntity;
import com.shanghaionstar.carmanage.service.ChargePileStationService;
import com.shanghaionstar.nav.model.LocateStatus;
import com.shanghaionstar.utils.NavHolder;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by 7828wc on 16/8/1.
 */
public class ChargingPilePresenter extends BasePresenter<List<ChargePileStationEntity>> {
    private IChargingPileView view;
    private ChargePileStationService service;
    private boolean isLoading = false;
    private String query = "";
    private List<ChargePileStationEntity> chargePileStationEntityList = new ArrayList<>();
    private BaseActivity mContext;

    private boolean isHaveNextPages = false;


    public ChargingPilePresenter(IMVPScheduler mvpScheduler) {
        super(mvpScheduler);
    }

    @Override
    public void setView(IMVPView<List<ChargePileStationEntity>> view) {
        super.setView(view);
        this.view = (IChargingPileView) view;
        service = new ChargePileStationService(view.onActivity());
        mContext = (BaseActivity) view.onActivity();
        mContext.requestRunTimePermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, new PermissionCall() {
            @Override
            public void requestSuccess() {
                getCurrentLocation();
            }

            @Override
            public void refused() {

            }
        });
    }

    private Subscription mLocalRx;

    public void getCurrentLocation() {
        mLocalRx = RxBus.getDefault().toObserverable(RxConstants.LOCATE, LocateStatus.class)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread()).subscribe(new Action1<LocateStatus>() {
                    @Override
                    public void call(LocateStatus pollingResult) {
                        if (pollingResult == LocateStatus.LOCATED) {
                            if (isLoading) {
//                        getChargingPileList(query);
                            }
                        } else {
                            if (isLoading)
                                view.onResponseError(new OnStarException(view.onActivity().getString(R.string.charging_network_error)));
                        }
                        isLoading = false;
                    }
                });
        NavHolder.getInstance(view.onActivity().getApplicationContext()).findMyLocation();
        RxSubscriptions.add(mLocalRx);
    }

    public void getChargingPileList() {
        getChargingPileList("");
    }

    public void clean() {
        chargePileStationEntityList.clear();
        service.setPageNumber(0);
    }

    public void getChargingPileList(final String query, String... args) {
        if (!chargePileStationEntityList.isEmpty()) {
            view.previewCheck(isHaveNextPages);
        }
        view.setLoading(true);
        isLoading = true;
        this.query = query;
        subscription = service.getCurrentLocaiton(query, args).flatMap(new Func1<ChargePileReqEntity, Observable<List<ChargePileStationEntity>>>() {
            @Override
            public Observable<List<ChargePileStationEntity>> call(ChargePileReqEntity entity) {
                if (entity != null) {
                    return service.getChargingPileList(entity);
                }
                return null;
            }
        }).subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread()).subscribe(new Action1<List<ChargePileStationEntity>>() {
                    @Override
                    public void call(List<ChargePileStationEntity> contentDetailDTO) {
                        isLoading = false;
                        try {
                            if (contentDetailDTO != null && !contentDetailDTO.isEmpty()) {
                                Log.d("addAll", "addAll");
                                isHaveNextPages = true;
                                chargePileStationEntityList.addAll(contentDetailDTO);
                                view.onReponseSuccess(chargePileStationEntityList);
                            } else {
                                isHaveNextPages = false;
                            }
                            if (chargePileStationEntityList.isEmpty()) {
                                view.showEmpty();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            view.onFailed(chargePileStationEntityList, isHaveNextPages, e.getMessage());
//                            view.onResponseError(ExceptionUtil.toOnStarException(e));
                        } finally {
                            view.setLoading(false);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        isLoading = false;
                        //抛出Error异常
//                        view.onResponseError((OnStarException) throwable);
                        view.onFailed(chargePileStationEntityList, isHaveNextPages, throwable.getMessage());
                        view.setLoading(false);
                    }
                });
    }

    public void onItemClick(int position) {
        ChargePileStationLocationFragment chargingPileStationLocationFragment = new ChargePileStationLocationFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(Constants.CHARGEPILEINFO, chargePileStationEntityList.get(position));
        chargingPileStationLocationFragment.setArguments(bundle);
        mContext.changeFragment(mContext.getSupportFragmentManager(), chargingPileStationLocationFragment,
                ChargePileStationLocationFragment.class, false);
    }

    public void onScrollStateChanged(AbsListView view, String... args) {
        if (view.getLastVisiblePosition() == view.getCount() - 1) {
            service.setPageNumber(service.getPageNumber() + 1);
//            pageNumber++;
            if (isHaveNextPages) {
                if(args !=null && args.length > 0)
                    getChargingPileList(query,args[0]);
                else
                    getChargingPileList(query);
            }
        }
    }

    @Override
    public void finish() {
        super.finish();
        RxSubscriptions.remove(mLocalRx);
    }
}
